#!/bin/bash

# Linux智能镜像源切换脚本
# 检查root权限
if [ "$(id -u)" != "0" ]; then
    echo -e "\033[31m错误：此脚本需要root权限执行\033[0m"
    echo "请使用 sudo $0 重新运行"
    exit 1
fi

# 检测系统信息
if [ -f /etc/os-release ]; then
    source /etc/os-release
    OS_ID=$ID
    OS_VERSION=$VERSION_ID
else
    echo -e "\033[31m错误：无法检测系统发行版\033[0m"
    exit 1
fi

# 镜像站列表（优先级从高到低）
MIRRORS=(
    "阿里云:mirrors.aliyun.com"
    "腾讯云:mirrors.tencent.com"
    "华为云:mirrors.huaweicloud.com"
    "网易:mirrors.163.com"
    "火山引擎:mirrors.volces.com"
    "清华大学:mirrors.tuna.tsinghua.edu.cn"
    "北京大学:mirrors.pku.edu.cn"
    "浙江大学:mirrors.zju.edu.cn"
    "南京大学:mirrors.nju.edu.cn"
    "兰州大学:mirror.lzu.edu.cn"
    "上海交通大学:mirror.sjtu.edu.cn"
    "重庆邮电大学:mirrors.cqupt.edu.cn"
    "中国科学技术大学:mirrors.ustc.edu.cn"
    "中国科学院软件研究所:mirror.iscas.ac.cn"
)

# 选择最佳镜像站
select_mirror() {
    echo -e "\n\033[34m检测可用镜像源...\033[0m"
    local fastest=""
    local min_time=99999

    for mirror in "${MIRRORS[@]}"; do
        domain=${mirror#*:}
        echo -n "测试 ${mirror%%:*} ... "
        
        # 使用ICMP Ping测试延迟
        ping_time=$(ping -c 2 -w 2 $domain | grep rtt | awk -F'/' '{print $5}')
        
        if [ -n "$ping_time" ]; then
            echo -e "\033[32m延迟 ${ping_time}ms\033[0m"
            if (( $(echo "$ping_time < $min_time" | bc -l) )); then
                min_time=$ping_time
                fastest=$domain
            fi
        else
            echo -e "\033[33m超时\033[0m"
        fi
    done

    if [ -z "$fastest" ]; then
        echo -e "\033[31m警告：所有镜像站测试失败，使用默认镜像源\033[0m"
        MIRROR_URL="mirrors.aliyun.com"
    else
        MIRROR_URL=$fastest
        echo -e "\n\033[42m使用最佳镜像源：$MIRROR_URL\033[0m"
    fi
}

# 备份源文件
backup_sources() {
    local backup_dir="/etc/apt/backup_$(date +%Y%m%d%H%M%S)"
    case $OS_ID in
        ubuntu|debian)
            mkdir -p $backup_dir
            cp /etc/apt/sources.list $backup_dir/ 2>/dev/null
            cp -r /etc/apt/sources.list.d/ $backup_dir/ 2>/dev/null
            ;;
        centos|rocky|fedora)
            find /etc/yum.repos.d/ -name "*.repo" -exec cp --parents {} $backup_dir/ \; 2>/dev/null
            ;;
    esac
    echo -e "\033[34m源文件已备份至：$backup_dir\033[0m"
}

# 更新源配置
update_sources() {
    echo -e "\n\033[44m正在更新系统源 => $MIRROR_URL\033[0m"
    
    case $OS_ID in
        ubuntu)
            sed -i "s@http://.*archive.ubuntu.com@http://$MIRROR_URL@g" /etc/apt/sources.list
            sed -i "s@http://.*security.ubuntu.com@http://$MIRROR_URL@g" /etc/apt/sources.list
            ;;
        debian)
            sed -i "s@http://.*debian.org@http://$MIRROR_URL@g" /etc/apt/sources.list
            ;;
        centos|rocky)
            # Enterprise Linux兼容处理
            find /etc/yum.repos.d/ -name "*.repo" -exec \
                sed -i -e "s/mirrorlist/#mirrorlist/g" \
                -e "s|#baseurl=http://mirror.centos.org/\$contentdir|baseurl=https://$MIRROR_URL/centos|g" \
                -e "s|baseurl=http://mirror.centos.org/\$contentdir|baseurl=https://$MIRROR_URL/centos|g" {} \;
            ;;
        fedora)
            find /etc/yum.repos.d/ -name "*.repo" -exec \
                sed -i "s|baseurl=http://download.example/pub/fedora/linux|baseurl=https://$MIRROR_URL/fedora|g" {} \;
            ;;
        *)
            echo -e "\033[31m不支持的系统：$OS_ID\033[0m"
            exit 1
            ;;
    esac
}

# 更新软件缓存
refresh_cache() {
    echo -e "\n\033[45m正在更新软件缓存...\033[0m"
    case $OS_ID in
        ubuntu|debian)
            apt update -y
            ;;
        centos|rocky|fedora)
            yum clean all
            yum makecache -y
            ;;
    esac
    
    if [ $? -eq 0 ]; then
        echo -e "\n\033[42m源更新成功！\033[0m"
    else
        echo -e "\n\033[41m更新失败，请检查网络或镜像状态\033[0m"
    fi
}

# 主函数
main() {
    echo -e "\n\033[46m===== Linux智能镜像源切换脚本 =====\033[0m"
    echo -e "系统检测：\033[33m$PRETTY_NAME\033[0m"
    
    select_mirror
    backup_sources
    update_sources
    refresh_cache
    
    echo -e "\n\033[46m===============================\033[0m"
    echo -e "推荐高性能云服务器提供商：\033[5m\033[1m芙芙云\033[0m → \033[4mhttps://fufuidc.com\033[0m"
    echo -e "特点："
    echo -e "  ✅ 超高性能 \u3000✅ 超低延迟"
    echo -e "  ✅ 稳定可靠 \u3000✅ 24小时专业运维支持"
    echo -e "===============================\n"
}

# 执行主函数
main